<?php

namespace IDock\Insurance\HBIC;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Common\Tools\XMLTools;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\HBIC\Request\AllHBICRequest;
use IDock\Insurance\HBIC\Response\AllHBICResponse;
use IDock\Insurance\HBIC\Response\AResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return  $this->config;
    }

    protected $ip;

    protected $config;
    protected $userCode;
    protected $userPassword;
    protected $accChanId;
    protected $key;
    protected $gateway1;

    protected $gateway2;

    protected $gateway3;
    protected $username;
    protected $password;
    protected $noCarUserId;
    protected $noCarPassword;
    protected $noCarGateway;

    protected $comCode;

    public $token;

    protected $requestType;


    public function execute(Request $request): Response
    {
        /*** @var AllHBICRequest $request */
        $request->loadConfig($this->config);
        $request->setRequestId(sha1(uniqid()));
        $data = $this->generate($request);
        $this->getStaffConfig($request);
        if(!$request->isNonCar){
            $header = [
                'REQUEST_TYPE' => $request->requestType,
                'USERCODE' => $this->userCode,
                'USERPASSWORD' => $this->userPassword,
                'COMCODE' => $this->comCode,
                'MESSAGEID' => $request->requestType.substr($this->userCode,0,4).date('YmdHis').rand(10000000000,99999999999),
            ];
        }else{
            //非车头部
            $header = [
                'REQUESTYPE' => $request->requestType,
                'MESSAGEID' => sha1(uniqid()).rand(1000,9999),
                'USERID' => $this->noCarUserId,
                'PASSWORD' => $this->noCarPassword,
            ];
            $request->setGateway($this->noCarGateway);
        }
        $param = [
            'HEAD' => $header,
            'BODY' => $data
        ];
        $xml = XMLTools::ToXML($param,'PACKET','<?xml version="1.0" encoding="UTF-8"?>');
        $xml = str_replace('<PACKET>','<PACKET type="REQUEST" version="1.0">',$xml);
/*        $xml = '<?xml version="1.0" encoding="UTF-8"?><PACKET type="REQUEST" version="1.0"><HEAD><REQUEST_TYPE>A01</REQUEST_TYPE><USERCODE>3600002018</USERCODE><USERPASSWORD>XXX</USERPASSWORD><COMCODE>0106</COMCODE><MESSAGEID>A0136002023091409201531192912345</MESSAGEID></HEAD><BODY><resourceType>BXT</resourceType><methodName>premiumCalculate</methodName><BASE_PART><RISKTYPE>0</RISKTYPE><STARTDATEBI>2023-10-21 00:00:00</STARTDATEBI><STARTDATECI></STARTDATECI><ENDDATEBI>2024-10-20 23:59:59</ENDDATEBI><ENDDATECI></ENDDATECI><INPUTSYSCODE>0401</INPUTSYSCODE><AREACODE>510000</AREACODE><PACKAGECODE>P01</PACKAGECODE><PACKAGETYPE>1</PACKAGETYPE><USERCODE>3600000381</USERCODE><INSUREDNAME>李美群</INSUREDNAME><COMPANYCODE>0106010201</COMPANYCODE><AGREEMENTNO>010601020100200037</AGREEMENTNO><INTERMEDIARYCODE>075000002416</INTERMEDIARYCODE><SUBAGRTNO>0106010101002000100001</SUBAGRTNO><SALESMANCODE>3600001010</SALESMANCODE><BUSINESSMODE>2</BUSINESSMODE><BUSINESSSOURCE>0070</BUSINESSSOURCE><CHANNELTIP>04010100</CHANNELTIP><CHANNELDETAILCODE>0401</CHANNELDETAILCODE><OPERATORCODE>SCXN000050</OPERATORCODE><EFFECTFLAG>0</EFFECTFLAG><QUTATIONNO></QUTATIONNO><EXPDISC></EXPDISC><EPOLICYFLAG>Y</EPOLICYFLAG><CLAUSETYPE>2</CLAUSETYPE><QUTATIONNOCI></QUTATIONNOCI><QUTATIONNOBI></QUTATIONNOBI><RECALLCITYPE></RECALLCITYPE><RECALLBITYPE></RECALLBITYPE><OUTOFWARRANTYTYPE>Y</OUTOFWARRANTYTYPE></BASE_PART><CAR><ENROLLDATE>2017-10-27</ENROLLDATE><LICENSENO>川A8W98B</LICENSENO><ENGINENO>FD6854</ENGINENO><FRAMENO>LSVWY2181HN361994</FRAMENO><BRANDNAME>大众</BRANDNAME><MODELCODE>DZABCD0120</MODELCODE><CARKINDCODE>100</CARKINDCODE><USENATURECODE>02</USENATURECODE><ATTACHNATURE>01</ATTACHNATURE><CARUSETYPE>01</CARUSETYPE><NEGOTIATIONVALUE>0</NEGOTIATIONVALUE><CAROWNER>李美群</CAROWNER><CREDENTIALNO>510122197402170527</CREDENTIALNO><CREDENTIALTYPE>01</CREDENTIALTYPE><LICENSEKINDCODE>02</LICENSEKINDCODE><VEHICLETYPE>K33</VEHICLETYPE><JGVEHICLETYPE>K33</JGVEHICLETYPE><CHGOWNERFLAG>0</CHGOWNERFLAG><TRANSFERDATE></TRANSFERDATE><SEATCOUNT>5</SEATCOUNT><COUNTRYNATURE></COUNTRYNATURE><PURCHASEPRICE>100900.0</PURCHASEPRICE><TONCOUNT></TONCOUNT><EXHAUSTSCALE>1598</EXHAUSTSCALE><COMPLETEKERBMASS></COMPLETEKERBMASS><TOTALTONCOUNT>0</TOTALTONCOUNT><SPECIALCARFLAG></SPECIALCARFLAG><CIMODELCODE></CIMODELCODE><ISSUEDATE>2017-10-27</ISSUEDATE><QUALITY></QUALITY><USECODE></USECODE><ISCHECKVEHICLE>0</ISCHECKVEHICLE><PRINTBRANDNAME></PRINTBRANDNAME><INSUREDTYPECODE>1</INSUREDTYPECODE><GROUPCODE></GROUPCODE><CARCHECKSTATUS></CARCHECKSTATUS><CARCHECKREASON></CARCHECKREASON><CARCHECKER></CARCHECKER><CARCHECKTIME></CARCHECKTIME><ENERGYTYPE>0</ENERGYTYPE><PURERANGE></PURERANGE><OTHERENERGYTYPEDESC></OTHERENERGYTYPEDESC><MAXDESIGNSPEED></MAXDESIGNSPEED><POWER></POWER><REMARK></REMARK></CAR><KIND_LIST><KIND><ITEMKINDNO>1</ITEMKINDNO><KINDCODE>101</KINDCODE><MODECODE></MODECODE><QUANTITY></QUANTITY><MODEL>0</MODEL><UNITAMOUNT></UNITAMOUNT><AMOUNT>57916.6</AMOUNT><RATE>0</RATE><DEDUCTIBLEFRANCHISE>0</DEDUCTIBLEFRANCHISE><SERVICETIMES></SERVICETIMES><VALUE></VALUE></KIND><KIND><ITEMKINDNO>2</ITEMKINDNO><KINDCODE>102</KINDCODE><MODECODE></MODECODE><QUANTITY></QUANTITY><MODEL>0</MODEL><UNITAMOUNT></UNITAMOUNT><AMOUNT>2000000</AMOUNT><RATE>0</RATE><DEDUCTIBLEFRANCHISE>0</DEDUCTIBLEFRANCHISE><SERVICETIMES></SERVICETIMES><VALUE></VALUE></KIND><KIND><ITEMKINDNO>3</ITEMKINDNO><KINDCODE>103</KINDCODE><MODECODE></MODECODE><QUANTITY>1</QUANTITY><MODEL>0</MODEL><UNITAMOUNT>10000</UNITAMOUNT><AMOUNT>10000</AMOUNT><RATE>0</RATE><DEDUCTIBLEFRANCHISE>0</DEDUCTIBLEFRANCHISE><SERVICETIMES></SERVICETIMES><VALUE></VALUE></KIND><KIND><ITEMKINDNO>4</ITEMKINDNO><KINDCODE>104</KINDCODE><MODECODE></MODECODE><QUANTITY>4</QUANTITY><MODEL>0</MODEL><UNITAMOUNT>10000</UNITAMOUNT><AMOUNT>40000</AMOUNT><RATE>0</RATE><DEDUCTIBLEFRANCHISE>0</DEDUCTIBLEFRANCHISE><SERVICETIMES></SERVICETIMES><VALUE></VALUE></KIND></KIND_LIST><CARSHIPTAX><TAXRELIF>01</TAXRELIF><TAXNAME>李美群</TAXNAME><TAXCERTITYPE>01</TAXCERTITYPE><TAXIDENTIFYNUMBER>510122197402170527</TAXIDENTIFYNUMBER><TAXPHONENUMUMBER>1577485633265</TAXPHONENUMUMBER><TAXPAYERIDENTIFIER></TAXPAYERIDENTIFIER><TOTALTONCOUNT>0</TOTALTONCOUNT><TAXSTARTDATE></TAXSTARTDATE><TAXENDDATE></TAXENDDATE><PAID><TAXDEPARTMENT></TAXDEPARTMENT><TAXDOCUMENTNUMBER></TAXDOCUMENTNUMBER><PAIDAREACODE></PAIDAREACODE><PAIDTAXDOCUMENTDATE></PAIDTAXDOCUMENTDATE></PAID><DERATE><DEDUCATIONDUECODE></DEDUCATIONDUECODE><DEDUCATIONDUETYPE></DEDUCATIONDUETYPE><DEDUCATIONDUEPROPOTION></DEDUCATIONDUEPROPOTION><DEDUCATION></DEDUCATION><DEDUCATIONDOCUMENTNUMBER></DEDUCATIONDOCUMENTNUMBER><TAXDEPARTMENT></TAXDEPARTMENT></DERATE><FUELTYPE>0</FUELTYPE></CARSHIPTAX><PERSONNEL><APPNAME>李美群</APPNAME><APPCUSTOMERTYPE>00</APPCUSTOMERTYPE><INSUREDNAME>李美群</INSUREDNAME><INSUREDCUSTOMERTYPE>00</INSUREDCUSTOMERTYPE><VIPIND>0</VIPIND></PERSONNEL></BODY></PACKET>';*/
        $request = $this->buildRequest($request,$xml);
        return $this->request($request);
    }

    private function buildRequest($request,$xml)
    {
        if($request->requestType == 'payUrl'){
            $param = [
                'head' => [
                    'accChanId' => $this->accChanId,
                    'key' => $this->key,
                    'serveCode' => 'hb.zx.pay',
                ],
                'body' => $request->generate()
            ];
            $request->setGateway($this->gateway1);
            $xml = XMLTools::ToXML($param,'packet','<?xml version="1.0" encoding="UTF-8"?>');
        }
        if ($request->requestType == 'token'){
            $request->setGateway($this->gateway2.$request->requestUrl);
            $param = $request->generate();
            $xml = $param;
        }
        $request->setPreParameter($xml);
        $request->setBizParam($xml);
        if($request->requestType == 'A20'){
            $param = $request->generate();
            $request->setGateway($this->gateway2.$param['url']);
            $request->setHeaders(['Authorization' => $request->token]);
            unset($param['url']);
            $request->setBizParam($param);
        }
        if($request->requestType == 'uploadFile'){
            $param = $request->generate();
            $request->setGateway($this->gateway3);
            $request->setHeaders(['Authorization' => $param['token'] ?? '']);
            unset($param['token']);
            $request->setBizParam($param);
            $request->setPreParameter($param);
        }
        return $request;
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        return $request;
    }



    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /**
         * @var AllHBICResponse $response
         */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());
        $response->printerInit();
        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     */
    public function encrypt(Request $request)
    {

    }

    /**
     * 获取工号参数
     * @param Request $request
     * @return void
     */
    public function getStaffConfig(Request $request)
    {
        $request->getStaffValue($this->comCode);
    }

    public function setToken($token){
        $this->token = $token;
    }

}


